﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDX.ContextManagement
{
    public class PropertyModelManager
    {
        Context Target { get; set; }
        IPropertyModelFactory PropertyModelFactory { get; set; }
        DefaultPropertyModel PropertyModel { get; set; }
        Notification.INotificationManager notifier = null;

        public PropertyModelManager(Context target, IPropertyModelFactory propModelFactory,
            Notification.INotificationManager notifier)
        {
            this.Target = target;
            this.PropertyModelFactory = propModelFactory;
            this.notifier = notifier;

            CreatePropertyModel();

            target.DependencyPropertyChanged += target_DependencyPropertyChanged;
            notifier.NotificationRaised += notifier_PropertyChanged;
        }

        void target_DependencyPropertyChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == Context.ResolutionProperty)
            {
                OnResolutionChanged();
            }
        }

        void CreatePropertyModel()
        {
            PropertyModel = PropertyModelFactory.CreatePropertyModel(Target) as DefaultPropertyModel;
            if (PropertyModel == null)
            {
                throw new Exception("Invalid PropertyModel type");
            }
            Target.SetValue(Context.PropertyModelProperty, PropertyModel);
        }

        void OnResolutionChanged()
        {
            Update();
        }

        void notifier_PropertyChanged(object sender, EventArgs e)
        {
            PropertyModel.CheckPropChanged();
        }

        void Update()
        {
            var resolution = Target.GetResolution();
            if (resolution == null)
            {
                return;
            }

            PropertyModel.DisplayName = resolution.Property.Name;
            PropertyModel.PropertyType = resolution.Property.PropertyType;

            PropertyModel.Getter = () => resolution.Property.GetValue(resolution.ResolvedDC, null);
            PropertyModel.Setter = (value) =>
                {
                    using (notifier.BeginDisposableTransaction())
                    {
                        resolution.Property.SetValue(resolution.ResolvedDC, value, null);
                    }
                };

            PropertyModel.Ext["OriginalDC"] = resolution.ResolvedDC;
        }
    }
}
